<template>
  <div>
    <h1 class="text-4xl font-bold">我的简历</h1>
    <ZForm
      ref="form"
      :initial-values="initialValues"
      :rules="rules"
      @success="onSuccess"
      #="{ cBinds, errors, resetForm }"
    >
      <div class="flex gap-4">
        <div class="flex w-full flex-col sm:w-1/3">
          <ZImgInput
            class="mx-auto block h-full w-full max-w-full rounded-2xl border-2 border-primary"
            alt="featured image"
            v-bind="cBinds.photo"
          >
            <div class="flex h-full flex-col items-center justify-center gap-4">
              <span class="icon-[uil--image-upload] h-12 w-12"></span>
              <h3>可以拖拽图片作为照片</h3>
            </div>
          </ZImgInput>
          <div class="my-2 font-semibold text-error">
            {{ errors?.photo }}
          </div>
        </div>
        <div class="flex-1">
          <ZFormItem label="姓名" name="name" :errors="errors">
            <ZInput v-bind="cBinds.name" />
          </ZFormItem>
          <ZFormItem label="职业" name="job" :errors="errors">
            <ZInput v-bind="cBinds.job" />
          </ZFormItem>
          <ZFormItem label="基本信息" name="basic" :errors="errors">
            <ZMdEditor class="h-40" v-bind="cBinds.basic" html xhtml-out />
          </ZFormItem>
        </div>
      </div>

      <ZFormItem label="联系方式" name="contact" :errors="errors">
        <ZMdEditor class="h-40" v-bind="cBinds.contact" html xhtml-out />
      </ZFormItem>
      <ZFormItem label="教育背景" name="education" :errors="errors">
        <ZMdEditor class="h-40" v-bind="cBinds.education" html xhtml-out />
      </ZFormItem>
      <ZFormItem label="技能" name="skills" :errors="errors">
        <ZMdEditor class="h-40" v-bind="cBinds.skills" html xhtml-out />
      </ZFormItem>
      <ZFormItem label="工作经验" name="workExperience" :errors="errors">
        <ZMdEditor class="h-64" v-bind="cBinds.workExperience" html xhtml-out />
      </ZFormItem>
      <div
        class="mx-auto mb-8 flex w-full max-w-5xl justify-end gap-4 px-4 lg:px-6"
      >
        <ZButton class="btn-primary" :loading="isFetching">保存简历</ZButton>
        <ZButton type="reset" class="btn-accent" @click="resetForm()">
          重置
        </ZButton>
      </div>
    </ZForm>
  </div>
</template>
<script setup lang="ts">
import { z } from "zod";
import ZForm from "@/components/forms/ZForm.vue";
import ZMdEditor from "@/components/forms/ZMdEditor.vue";
import { useApiFetch, ApiResponse } from "@/composables/useApiFetch";
import ZFormItem from "@/components/forms/ZFormItem.vue";

const rules = z.object({
  name: z.string().min(2, "至少要2个字符").max(50, "不能超过50个字符"),
  job: z.string().min(2, "至少要2个字符").max(50, "不能超过50个字符"),
  photo: z.any().superRefine((val, ctx) => {
    if (!val) {
      return ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "照片不能为空",
      });
    }
    const file = val as File;
    if (file.size >= 800 * 1024) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "照片不能超过800KB",
      });
    }
  }),
  basic: z.string().min(2, "至少要2个字符"),
  contact: z.string().min(2, "至少要2个字符"),
  education: z.string(),
  skills: z.string(),
  workExperience: z.string(),
});
const initialValues: z.infer<typeof rules> = {
  name: "",
  job: "",
  photo: null,
  basic: "",
  contact: "",
  education: "",
  skills: "",
  workExperience: "",
};
const form = ref<InstanceType<typeof ZForm>>();
// 获取简历
const { data: resume, execute } = useApiFetch("/user/resume", {
  immediate: false,
}).json<ApiResponse>();
watch(resume, (val) => {
  if (val?.success) {
    form.value?.resetForm({ values: val.object });
  }
});
onActivated(() => execute());
// 保存简历
const {
  post: saveResume,
  isFetching,
  data,
} = useApiFetch("/user/resume", { immediate: false }).json<ApiResponse>();
const onSuccess = async (values: any) => {
  // 图片字段需要使用FormData
  const formData = new FormData();
  Object.entries(values).forEach(([key, value]) => {
    if (value instanceof File) formData.append(key, value, value.name);
    else formData.append(key, value as string);
  });
  //
  await saveResume(formData).execute();
  if (data.value?.success) {
    form.value?.resetForm({ values: data.value.object });
  } else {
    if (data.value?.errors) form.value?.setErrors(data.value?.errors);
  }
};
</script>
